package com.lz.comm.widget.camera

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.view.TextureView

/**
 * 用于显示Camera数据的TextureView,提供suface
 * Created by You on 2020-02-13.
 */
class CameraView : TextureView {

    private lateinit var gestureDetector: GestureDetector

    private lateinit var scaleGestureDetector: ScaleGestureDetector

    private var currentScale = 1.0f

    var maxScale = Float.MAX_VALUE

    var listener: OnCameraGestureListener? = null

    constructor(context: Context) : super(context) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init(context)
    }

    private fun init(context: Context) {
        gestureDetector = GestureDetector(context, SimpleGestureListener())
        scaleGestureDetector = ScaleGestureDetector(context, SimpleScaleListener())
        isClickable = false
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        val res = scaleGestureDetector.onTouchEvent(event)
        return if (!scaleGestureDetector.isInProgress) gestureDetector.onTouchEvent(event) else res
    }

    private inner class SimpleScaleListener : ScaleGestureDetector.SimpleOnScaleGestureListener() {
        override fun onScale(detector: ScaleGestureDetector): Boolean {
            currentScale *= detector.scaleFactor
            if (currentScale < 1.0f) currentScale = 1.0f
            if (currentScale > maxScale) currentScale = maxScale
            listener?.onHandleZoom(currentScale)
            return true
        }
    }

    private inner class SimpleGestureListener : GestureDetector.SimpleOnGestureListener() {
        override fun onDown(e: MotionEvent): Boolean = true

        override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
            listener?.onHandleFocus(e.x, e.y, width, height)
            return super.onSingleTapConfirmed(e)
        }
    }

    /**
     * 相机手势操作, 点击聚集与缩放预览
     */
    interface OnCameraGestureListener {
        /**
         * 缩放手势
         * @param zoomScale 放大比例
         */
        fun onHandleZoom(zoomScale: Float)

        /**
         * 聚集坐标
         * @param x
         * @param y
         * @param w
         * @param h
         */
        fun onHandleFocus(x: Float, y: Float, w: Int, h: Int)
    }
}